/*******************************************************************************
 * Package: com.hadoop.mr
 * Type:    WordCountLocalMain
 * Date:    2024-05-15 10:18
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hadoop.mr;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;

/**
 * 功能描述： 本地读 本地写 数据写入到 本地
 * 一般在本地处理完成后在发布到线上一个 任务调度
 * 写本地 https://www.cnblogs.com/zmqs/articles/18145920
 * @author Songxianyang
 * @date 2024-05-15 10:18
 */
public class WordCountLocalMain {

    public static void main(String[] args) throws Exception{
        Job job = Job.getInstance();
        // 设置启动类
        job.setJarByClass(WordCountMain.class);

        // 设置 map 、reduce 类
        job.setMapperClass(WordCountMapper.class);
        job.setReducerClass(WordCountReduce.class);

        // map 输出 类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        //Reduce 输出类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        // 设置 Combiner 减少开销 在map端先聚合一下 在传送给reduce
        job.setCombinerClass(WordCountCombiner.class);

        // 创建输入目录
        Path inputPath = new Path("D:\\work\\project\\gitee-github\\hadoop\\input\\mr\\input.txt");
        // 创建输出目录
        Path outputPath = new Path("D:\\work\\project\\gitee-github\\hadoop\\output\\mr\\");

        // 如果存在就删除
        File folder = new File(outputPath.toString());
        if (folder.exists()) {
            deleteFiles(folder);
        }

        // 设置 FileInputFormat   FileOutputFormat
        FileInputFormat.setInputPaths(job,inputPath);
        FileOutputFormat.setOutputPath(job,outputPath);
        boolean result = job.waitForCompletion(true);
        System.exit(result ? 0 : 1);
    }


    private static void deleteFiles(File file) {
        if (file.isDirectory()) {
            // 如果是文件夹，则遍历其中的文件并递归删除
            for (File subFile : file.listFiles()) {
                deleteFiles(subFile);
            }
        }

        // 删除文件或空文件夹
        if (file.delete()) {
            System.out.println("已成功删除：" + file.getAbsolutePath());
        } else {
            System.out.println("删除失败：" + file.getAbsolutePath());
        }
    }

}
